<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRolesVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rolesList" border stripe>
        <!-- 添加表格展开域 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 一级权限 -->
            <el-row
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
              :class="['center','bdb', i1 === 0 ?'bdt':'']"
            >
              <el-col :span="5">
                <el-tag closable @close="removeRightsById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <!-- 二级权限 -->
                <el-row
                  :class="['center',i2 ==0 ? '':'bdt']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <!-- 三级权限 -->
                    <el-tag
                      closable
                      @close="removeRightsById(scope.row,item2.id)"
                      type="success"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      closable
                      @close="removeRightsById(scope.row,item3.id)"
                      type="warning"
                      v-for="(item3) in item2.children"
                      :key="item3.id"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{scope.row}}</pre> -->
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="角色操作" width="300px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="getRoleInfo(scope.row.id)"
              size="mini"
            >编辑</el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeRoleById(scope.row.id)"
            >删除</el-button>
            <!-- 权限分配按钮 -->
            <el-button
              type="warning"
              @click="showSetRightDialog(scope.row)"
              icon="el-icon-s-tools"
              size="mini"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addRolesVisible" width="50%" @close="resetaddRoleForm">
      <!-- 表单区域 -->
      <el-form
        :model="addRoleForm"
        :rules="addRoleFormrules"
        ref="addRoleFormRef"
        label-width="90px"
      >
        <!-- prop是要校验时候的规则名 -->
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="subaddRoleForm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色的对话框 -->
    <el-dialog title="修改角色" :visible.sync="editDialogVisible" width="50%">
      <!-- 表单区域 -->
      <!-- 因为验证方式相同，所以rules可以也绑定到addFormrules上 -->
      <el-form
        ref="editRoleFormRef"
        :model="editRoleForm"
        :rules="addRoleFormrules"
        label-width="90px"
        @close="reseteditRoleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="showRightDialog"
      width="30%"
      @close="showRightDialogClosed"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="rightsList"
        :props="treeProps"
        :default-checked-keys="defKey"
        :default-expand-all="true"
        node-key="id"
        show-checkbox
        ref='treeRef'
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showRightDialog = false">取 消</el-button>
        <el-button type="primary" @click="allotRigths">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      // 角色列表
      rolesList: [],
      addRolesVisible: false,
      // 添加表单对象
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      addRoleFormrules: {
        roleName: [{ required: true, message: '请输入角色名', trigger: 'blur' }]
      },
      editDialogVisible: false,
      // 编辑表单对象
      editRoleForm: {},
      showRightDialog: false,
      // 权限列表
      rightsList: {},
      // 树形控件的属性绑定
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 树形控件默认选中的数组
      defKey: [],
      // 即将分配权限的角色的id
      roleId: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      }
      this.rolesList = res.data
      // console.log(res)
    },
    // 重置对话框
    resetaddRoleForm () {
      this.$refs.addRoleFormRef.resetFields()
    },
    // 提交添加角色
    subaddRoleForm () {
      this.$refs.addRoleFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addRoleForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败')
        }
        this.$message.success('添加角色成功')
        // console.log(result.data)
        this.addRolesVisible = false
        this.getRolesList()
      })
    },
    // 还原对话框
    reseteditRoleForm () {
      this.$refs.editRoleFormRef.resetFields()
    },
    // 通过id获取角色
    async getRoleInfo (id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色信息失败')
      }
      this.editRoleForm = res.data
      // console.log(res.data)

      this.editDialogVisible = true
    },
    // 编辑角色
    editUserInfo () {
      this.$refs.editRoleFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'roles/' + this.editRoleForm.roleId,
          {
            roleName: this.editRoleForm.roleName,
            roleDesc: this.editRoleForm.roleDesc
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('编辑角色失败')
        }
        this.$message.success('编辑角色成功')
        // console.log(result.data)
        this.editDialogVisible = false
        this.getRolesList()
      })
    },
    // 通过id删除角色
    async removeRoleById (id) {
      // confirm返回的是一个primise实例对象
      // 点击确定会返回一个 confirm字符
      const result = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // catch捕捉点击取消时候的报错
      if (result !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除角色失败')
      this.$message.success('删除角色成功')
      this.getRolesList()
    },
    // 通过id删除权限
    async removeRightsById (role, rightId) {
      const result = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (result !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) return this.$message.error('删除权限失败')
      this.$message.success('删除权限成功')
      // console.log(res)
      role.children = res.data
    },
    // 展示权限对话框
    async showSetRightDialog (role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      }
      // console.log(res)
      this.rightsList = res.data
      this.getleafKeys(role, this.defKey)
      this.showRightDialog = true
    },
    // 通过递归的方式获得角色下所有的三级权限的id,并且保存到数组defKey中
    getleafKeys (node, arr) {
      // 如果一个节点不包含children属性，那么就是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getleafKeys(item, arr)
      })
    },
    // 关闭对话框时清空列表默认选中列表
    showRightDialogClosed () {
      this.defKey = []
    },
    // 确认分配权限
    async allotRigths () {
      const keys = [ ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: idStr
      })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('权限分配成功')
      this.getRolesList()
      this.showRightDialog = false
    }
  }
}
</script>
<style lang='less' scoped>
.el-tag {
  margin: 7px;
}
.bdb {
  border-bottom: 1px solid #eee;
}
.bdt {
  border-top: 1px solid #eee;
}
 /* 让展开行垂直居中 */
.center {
  display: flex;
  align-items: center;
}
</style>
